package com.atguigu.flink.chapter11.window;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Over;
import org.apache.flink.table.api.OverWindow;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.*;

/**
 * @Author lzc
 * @Date 2022/11/1 08:48
 */
public class Flink_04_Window_Over {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("s1", 1000L, 10),
                new WaterSensor("s1", 2000L, 20),
                new WaterSensor("s1", 2000L, 30),
                new WaterSensor("s1", 4000L, 40),
                new WaterSensor("s1", 5000L, 50),
                new WaterSensor("s1", 6000L, 60)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            );
    
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        Table table = tEnv.fromDataStream(stream, $("id"), $("ts").rowtime(), $("vc"));
        // 1. table api中使用 over 窗口
        // sum(..) over(partition by id order by ts rows between unbounded preceding and current row )
        // sum(..) over(partition by id order by ts  )
    
//        OverWindow win = Over.partitionBy($("id")).orderBy($("ts")).preceding(UNBOUNDED_ROW).following(CURRENT_ROW).as("w");
       // OverWindow win = Over.partitionBy($("id")).orderBy($("ts")).preceding(Expressions.rowInterval(1L)).following(CURRENT_ROW).as("w");
//        OverWindow win = Over.partitionBy($("id")).orderBy($("ts")).preceding(UNBOUNDED_RANGE).following(CURRENT_RANGE).as("w");
//        OverWindow win = Over.partitionBy($("id")).orderBy($("ts")).preceding(lit(2).second()).following(CURRENT_RANGE).as("w");
        OverWindow win = Over.partitionBy($("id")).orderBy($("ts")).as("w"); // UNBOUNDED_RANGE => CURRENT_RANGE
        
        table
            .window(win)
            .select($("id"), $("ts"), $("vc"), $("vc").sum().over($("w")).as("vc_sum"))
            .execute()
            .print();
        
    }
}
